package com.example.nfctagcommons.utils;

import com.example.nfctagcommons.exceptions.ConnectivityException;
import com.example.nfctagcommons.server.ServerConnector;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.SystemClock;

public class SystemConstants {
	private static long serverTime;
	private static long startTime;
	
	public static synchronized long getTime() {
		long threadTime = SystemClock.elapsedRealtime() - startTime;
		return SystemConstants.serverTime + threadTime;
	}
	public static synchronized void syncTime(final Activity activity) {
		if (SystemConstants.serverTime == 0){
			AsyncTask<Void, Void, Void> timeSynchronizer = new AsyncTask<Void, Void, Void>(){
				@Override
				protected Void doInBackground(Void... params) {
					try {
						if (SystemConstants.serverTime == 0){
							SystemConstants.serverTime = ServerConnector.synchronizeTime(activity);
							startTimer();
						}
					} catch (ConnectivityException e) {
						e.printStackTrace();
					}
					return null;
				}
			};
			if (android.os.Build.VERSION.SDK_INT > 10) {
				timeSynchronizer.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
			}else{
				timeSynchronizer.execute();
			}
		}
	}
	
	public static void startTimer(){
		startTime = SystemClock.elapsedRealtime();
	}
	
}
